(function($, doc) {
	$.init();
	$.plusReady(function() {
		//var id = plus.webview.currentWebview().id;
		//console.log(id);
		//var settings = app.getSettings();
		var regfid = doc.getElementById('fid');
		var regButton = doc.getElementById('reg');
		var accountBox = doc.getElementById('account');
		var passwordBox = doc.getElementById('password');
		var tradepwdBox = doc.getElementById('tradepwd');
		var nicknameBox = doc.getElementById('nickname');
		var usernameBox = doc.getElementById('user_name');
		var sexBox = doc.getElementById('sex');
		var passwordConfirmBox = doc.getElementById('password_confirm');
		var img = doc.getElementById('head-img1').src;

		//localStorage.removeItem('_send_code');

		//点击获取验证码
		document.getElementById("getCode").addEventListener('tap', function() {
			//localStorage.removeItem('_send_code');
			var c1 = 60,
				phone = document.getElementById('account').value;
			//			if(!phone || !(/^1(3|4|5|7|8)\d{9}$/.test(phone))) {
			//				plus.nativeUI.toast("手机号码有误，请重填手机号");
			//				return;
			//			}
			if(!phone) {
				plus.nativeUI.toast("手机号码不能为空");
				return;
			}
			//return;
			var btnArray = ['确定', '取消'];
			mui.confirm('我们将发送验证码短信到下面的号码：\n' + phone, '确认手机号码', btnArray, function(e) {
				if(e.index == 0) {

					mui.get(apiurl + 'index/regsms', {
						'phone': phone,
						'areacode': document.getElementById('area_code').value
					}, function(res) {
						if(res.status == 1) {
							//发送短信成功
							//localStorage.setItem('_send_code', res.ck_code);
							plus.nativeUI.toast("发送成功！");
						} else {
							plus.nativeUI.toast(res.msg);
							document.getElementById('getCode').innerHTML = '获取验证码';
							document.getElementById('getCode').removeAttribute('disabled');
							c1 = 60;
							return;
						}
						var code1 = setInterval(function() {
							document.getElementById('getCode').innerHTML = c1 + '秒后重新获取';
							c1 = c1 - 1;
							if(c1 >= 0) {
								document.getElementById('getCode').setAttribute("disabled", "disabled");
							} else {
								document.getElementById('getCode').innerHTML = '获取验证码';
								document.getElementById('getCode').removeAttribute('disabled');
								c1 = 60;
								clearInterval(code1);
							}
						}, 1000);
					});

				}
			})

		});

		regButton.addEventListener('tap', function(event) {
			var regInfo = {
				fid: regfid.value,
				account: accountBox.value,
				password: passwordBox.value,
				tradepwd: tradepwdBox.value,
				nickname: nicknameBox.value,
				username: usernameBox.value,
				sex: sexBox.classList.contains("mui-active") ? 1 : 0,
				phone_country: doc.getElementById('country').value,
				phone_code: doc.getElementById('area_code').value,
				file: doc.getElementById('avatar').value,
				code: doc.getElementById('code').value
			};
			/*
			var passwordConfirm = passwordConfirmBox.value;
			if(passwordConfirm != regInfo.password) {
				plus.nativeUI.toast('密码两次输入不一致');
				return;
			}
			if(!(/^1(3|4|5|7|8)\d{9}$/.test(regInfo.account))) {
				plus.nativeUI.toast("手机号码有误，请重填");
				return;
			}*/
			if(app.checkPwd(regInfo.password, 6) === false) {
				plus.nativeUI.toast('登录密码必6位以上');
				return;
			}
			if(app.checkPwd(regInfo.tradepwd, 6) === false) {
				plus.nativeUI.toast('交易密码必6位以上');
				return;
			}
			if(regInfo.nickname.length < 2) {
				plus.nativeUI.toast('昵称最短需要 2 个字符');
				return;
			}
			if(regInfo.username.length < 4) {
				plus.nativeUI.toast('用户名最短需要 4 个字符');
				return;
			}
			if(doc.getElementById('code').value == '') {
				plus.nativeUI.toast('请填写验证码');
				return;
			}
			/*
			if(!localStorage.getItem('_send_code')) {
				plus.nativeUI.toast('请获取验证码');       
				return;
			}

			if(doc.getElementById('code').value.trim() != localStorage.getItem('_send_code')) {
				mui.alert('验证码错误');
				return;
			}*/

			if(doc.getElementById('avatar').value == '') {
				//plus.nativeUI.toast('请上传头像');
				//return;
			}
			regInfo.passwd = md5(regInfo.password);
			regInfo.tradepwd = md5(regInfo.tradepwd);
			console.log(JSON.stringify(regInfo));
			console.log(regurl);
			mui.post(regurl, regInfo, function(data) {
				console.log(JSON.stringify(data));
				//localStorage.removeItem('_send_code');
				if(!data.status) {
					if(data.msg) {
						mui.alert(data.msg);
					} else {
						mui.alert("注册失败！");
					}

					return;
				}
				data.userinfo.pwd = regInfo.passwd;
				data.userinfo.password = regInfo.password;
				app.addUsers(data.userinfo);
				app.createState(data.userinfo);
				app.setLoginInfo(data.userinfo);
				mui.toast('您是第' + data.userinfo.user_id + '位用户');
				setTimeout(function() {
					location.href = 'main.html';
				}, 500);

				//toMain();
				/*
				plus.webview.getLaunchWebview().show("pop-in", 200, function() {
					plus.webview.currentWebview().close("none");
				});*/
			});

		});
	});

	//添加自定义事件监听
	window.addEventListener('update_code', function(event) {
		//获得事件参数
		var country = event.detail.name;
		var area_code = event.detail.code;
		//console.log(area_code);
		document.getElementById('type').value = country + '  (+' + area_code + ')';
		document.getElementById('country').value = country;
		document.getElementById('area_code').value = area_code;
	});

	function edit_nickname() {
		var ck_ed = cheche_edit();
		if(ck_ed) {
			document.getElementById('reg').removeAttribute('disabled');
		} else {
			document.getElementById('reg').setAttribute('disabled', 'disabled');
		}
	}

	function edit_phone(obj) {
		var ck_ed = cheche_edit();
		if(ck_ed) {
			document.getElementById('reg').removeAttribute('disabled');
		} else {
			document.getElementById('reg').setAttribute('disabled', 'disabled');
		}
		//
		//		if(!(/^1(3|4|5|7|8)\d{9}$/.test(obj.value))) {
		//			mui('.mui-icon.mui-icon-closeempty')[0].style.display = 'block';
		//		} else {
		//			mui('.mui-icon.mui-icon-closeempty')[0].style.display = 'none';
		//		}

		if(obj.value == '') {
			mui('.mui-icon.mui-icon-closeempty')[0].style.display = 'none';
		}
	}

	function edit_pwd() {
		var ck_ed = cheche_edit();
		if(ck_ed) {
			document.getElementById('reg').removeAttribute('disabled');
		} else {
			document.getElementById('reg').setAttribute('disabled', 'disabled');
		}
	}

	function cheche_edit() {
		if(document.getElementById('nickname').value == '') {
			return false;
		}
		if(document.getElementById('account').value.trim() == '') {
			return false;
		}
		/*
		if(!(/^1(3|4|5|7|8)\d{9}$/.test(document.getElementById('account').value))) {
			return false;
		}*/
		if(document.getElementById('password').value.trim() == '') {
			return false;
		}

		return true;
	}
	//点击国家/地区
	document.getElementById("nation").addEventListener('tap', function() {

		mui.openWindow({
			url: 'pages/login/nation_list.html',
			id: 'nation_list.html'
		});

	});

	//更换头像
	mui(".mui-table-view-cell").on("tap", "#head", function(e) {
		if(mui.os.plus) {
			var a = [{
				title: "拍照"
			}, {
				title: "从手机相册选择"
			}];
			plus.nativeUI.actionSheet({
				title: "上传头像",
				cancel: "取消",
				buttons: a
			}, function(b) {
				switch(b.index) {
					case 0:
						break;
					case 1:
						getImage();
						break;
					case 2:
						galleryImg();
						break;
					default:
						break
				}
			})
		}

	});

	function uploadImg(path) {
		var img = new Image();
		img.src = path;
		img.onload = function() {
			var that = this;
			//生成比例 
			var w = that.width,
				h = that.height,
				scale = w / h;
			w = 480 || w; //480  你想压缩到多大
			h = w / scale;

			//生成canvas
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			canvas.setAttribute('width', w);
			canvas.setAttribute('height', h);
			ctx.drawImage(that, 0, 0, w, h);
			var base64 = canvas.toDataURL('image/jpeg', 0.8); //1z 表示图片质量，越低越模糊。	 
			//console.log(base64);
			//base64 = base64.replace('data:image/jpeg;base64,', '');

			//document.getElementById('avatar').value = base64;
			mui.post(upurl, {
				file: base64,
				uid: 9,
				path: path,
                isavatar: 1
			}, function(res) {
				//console.log(res);
				res = JSON.parse(res);
				if(res.status > 0) {
					document.getElementById('avatar').value = res.url;
				}
			});
		}
	};

	function getImage() {
		var c = plus.camera.getCamera();
		c.captureImage(function(e) {
			plus.io.resolveLocalFileSystemURL(e, function(entry) {
				var s = entry.toLocalURL() + "?version=" + new Date().getTime();
				console.log(s);
				document.getElementById("head-img1").src = s;
				uploadImg(s);
				//变更大图预览的src
				//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
				document.querySelector("#__mui-imageview__group .mui-slider-item img").src = s + "?version=" + new Date().getTime();
			}, function(e) {
				console.log("读取拍照文件错误：" + e.message);
			});
		}, function(s) {
			console.log("error" + s);
		}, {
			filename: "_doc/head.jpg"
		})
	}

	function galleryImg() {
		plus.gallery.pick(function(a) {
			plus.io.resolveLocalFileSystemURL(a, function(entry) {
				plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
					root.getFile("head.jpg", {}, function(file) {
						//文件已存在
						file.remove(function() {
							console.log("file remove success");
							entry.copyTo(root, 'head.jpg', function(e) {
									var e = e.fullPath + "?version=" + new Date().getTime();
									document.getElementById("head-img1").src = e;
									uploadImg(e);
									//document.getElementById("head-img1").src = e;
									//变更大图预览的src
									//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
									document.querySelector("#__mui-imageview__group .mui-slider-item img").src = e + "?version=" + new Date().getTime();;
								},
								function(e) {
									console.log('copy image fail:' + e.message);
								});
						}, function() {
							console.log("delete image fail:" + e.message);
						});
					}, function() {
						//文件不存在
						entry.copyTo(root, 'head.jpg', function(e) {
								var path = e.fullPath + "?version=" + new Date().getTime();
								document.getElementById("head-img1").src = path;
								//document.getElementById("head-img1").src = path;
								//变更大图预览的src
								//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
								document.querySelector("#__mui-imageview__group .mui-slider-item img").src = path;
							},
							function(e) {
								console.log('copy image fail:' + e.message);
							});
					});
				}, function(e) {
					console.log("get _www folder fail");
				})
			}, function(e) {
				console.log("读取拍照文件错误：" + e.message);
			});
		}, function(a) {}, {
			filter: "image"
		})
	};

}(mui, document));